package net.xi.news.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Builder;
import net.xi.news.dao.SysUserMapper;
import net.xi.news.dao.UserMapper;
import net.xi.news.pojo.SysUser;
import net.xi.news.pojo.User;
import net.xi.news.service.RedisService;
import net.xi.news.service.UserService;
import net.xi.news.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;


@Service
public class UserServiceImpl extends ServiceImpl<SysUserMapper,SysUser> implements UserService {

    @Autowired
    private UserMapper userRespository;

    @Autowired
    private RedisService redisService;

    @Override
    //查找用户实现匹配
    public User checkUser(String username, String password) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.eq("password",MD5Utils.code(password));
        User user = userRespository.selectOne(queryWrapper);
        return user;
    }

    /**
     * 按id查询用户
     * @param id
     * @return
     */
    @Override
    public SysUser findUserById(Long id){
        String json = redisService.get("NEWS_USER_" + id);
        if (StringUtils.isEmpty(json)){
            SysUser user = this.getById(id);
            if (!ObjectUtils.isEmpty(user)){
                String userjson = JSON.toJSONString(user);
                redisService.set("NEWS_USER_"+id,60*60*60,userjson);
            }
            return user;
        }else {
            SysUser sysUser = JSON.parseObject(json, SysUser.class);
            return sysUser;
        }

    }
}
